//
//  ClassifyViewController.m
//  TerritoryShopkeeper
//
//  Created by xiaowu on 2017/11/27.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "ClassifyViewController.h"
#import "ClassifyTitleView.h"
#import "ClassifyListCell.h"
#import "ClassifyTableViewItemCell.h"
#import "GoodsListViewController.h"

@interface ClassifyViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) ClassifyTitleView *titleView;
@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *firstArr;
@property (nonatomic, assign) NSInteger index;
@end

@implementation ClassifyViewController
#pragma mark - Life
- (instancetype)init {
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = NO;
        self.navigationItem.title = @"分类";
        _firstArr = [NSMutableArray array];
        _index = 0;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [self configureUI];
    [self loadNetWork];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self hiddenShadowImage:NO];
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.titleView.frame = CGRectMake(0, 0, 74, self.view.height);
    self.collectionView.frame = CGRectMake(74, 0, self.view.width - 74, self.view.height);
}

- (void)configureUI {
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.collectionView];
    
    __weak typeof(self) weakSelf = self;
    self.titleView.block = ^(NSInteger index) {
        NSLog(@"%ld", (long)index);
        [weakSelf scrollIndexOrSelectIndex:index];
        [weakSelf.collectionView scrollRectToVisible:CGRectMake(74, weakSelf.collectionView.height * index, weakSelf.collectionView.width, weakSelf.collectionView.height) animated:YES];
        
        //        [weakSelf setHeadLabelText:model.gcname WithImageUrl:model.gcimg];
    };
    
    //    self.navigationItem.leftBarButtonItem = nil;
    
    //    self.navigationItem.titleView = self.searchBar;
    //    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[UIView new]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[UIView new]];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[UIView new]];
}

- (void)reloadUI {
    [self.titleView setupWithTitleStrsArr:[self getFirstStr:self.firstArr] withIndex:self.index];
        
    [self.collectionView reloadData];
}

- (NSMutableArray *)getFirstStr:(NSArray *)arr {
    NSMutableArray *firstArr = [NSMutableArray array];
    
    for (ClassifyFirstModel *model in self.firstArr) {
        [firstArr addObject:model.gcname];
    }
    
    return firstArr;
}

#pragma mark - NetWork
- (void)loadNetWork {
    [self getFirstClass];
}

- (void)getFirstClass {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_All_Class parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSArray *data = [responseDic safeJsonObjectForKey:@"data"];
            [weakSelf.firstArr removeAllObjects];
            for (NSDictionary *modelDic in data) {
                ClassifyFirstModel *model = [ClassifyFirstModel mj_objectWithKeyValues:modelDic];
                [weakSelf.firstArr addObject:model];
            }
            [weakSelf reloadUI];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:nil animated:YES];
    } isNeedCache:NO];
}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.firstArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    ClassifyTableViewItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"tableViewCell" forIndexPath:indexPath];
    
    ClassifyFirstModel *firstModel = [self.firstArr safeObjectAtIndex:indexPath.row];
    [cell setTableViewData:firstModel.twoclass withTitle:firstModel.gcname withImageUrl:firstModel.gcimg];
    
    cell.block = ^(NSInteger section, NSInteger index) {
        ClassifyFirstModel *firstModel = [weakSelf.firstArr objectAtIndex:indexPath.row];
        ClassifySecondModel *secondModel = [firstModel.twoclass objectAtIndex:section];
        ClassifyThirdModel *thirdModel = [secondModel.threeclass objectAtIndex:index];
        NSLog(@"third.gtrcid = %@", thirdModel.gtrcid);
        
        GoodsListViewController *goodsListVC = [[GoodsListViewController alloc] init];
        goodsListVC.navigationItem.title = thirdModel.gtrcname;
        goodsListVC.gcid = firstModel.gcid;
        goodsListVC.gtcid = secondModel.gtcid;
        goodsListVC.gtrcid = thirdModel.gtrcid;
        [weakSelf.navigationController pushViewController:goodsListVC animated:YES];
    };
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.view.width - 74, self.view.height);
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    //    SearchCacheViewController *searchCacheVC = [[SearchCacheViewController alloc] init];
    //    [self.navigationController pushViewController:searchCacheVC animated:YES];
    
    return NO;
}

#pragma mark - UIScrollViewDeleagte
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView != self.collectionView) {
        return;
    }
    CGFloat y = scrollView.contentOffset.y;
    CGFloat page = y / self.view.height;
    NSInteger index = (page + 0.3) / 1;
    [self.titleView setToShowIndex:index withAnimation:YES];
    [self scrollIndexOrSelectIndex:index];
    NSLog(@"scrollViewDidEndDecelerating: %f, index:%ld", page, (long)index);
}

- (void)scrollIndexOrSelectIndex:(NSInteger)index {
    self.index = index;
    //    ClassifyFirstModel *firstModel = [self.firstArr safeObjectAtIndex:index];
    //    [self getSecondClass:firstModel.gcid];
}

#pragma mark - Getters
- (ClassifyTitleView *)titleView {
    if (!_titleView) {
        _titleView = [[ClassifyTitleView alloc] init];
    }
    return _titleView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.delegate = self;
        [_searchBar setTintColor:[UIColor blueColor]];
        _searchBar.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor]];
        //        [_searchBar changeLeftPlaceholder:@"搜索你想要的"];
        _searchBar.placeholder = @"搜索你感兴趣的商品";
        
        UITextField *searchField = [_searchBar valueForKey:@"searchField"];
        searchField.mj_h = 28;
        [searchField.layer setCornerRadius:14];
        //[searchField.layer setBorderWidth:0.5];
        searchField.backgroundColor = [UIColor colorWithHex:0xEAEBED  alpha:1.0];
        [searchField.layer setBorderColor:[UIColor lightGrayColor].CGColor];
        searchField.layer.masksToBounds = YES;
    }
    return _searchBar;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.itemSize = CGSizeMake(ScreenWidth - 74, self.view.height);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical; // 纵向
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.pagingEnabled = YES;
        _collectionView.alwaysBounceHorizontal = YES;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.bounces = NO;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"ClassifyTableViewItemCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"tableViewCell"];
    }
    return _collectionView;
}

@end
